package com.ruoyi.web.controller.system;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ItoPush;
import com.ruoyi.common.core.domain.entity.ItoResume;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.vo.LineResponseVo;
import com.ruoyi.system.domain.vo.PieResponseVo;
import com.ruoyi.system.service.IItoPushService;
import com.ruoyi.system.service.IItoResumeService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2022-10-12
 */
@RestController
@RequestMapping("/system/resume")
public class ItoResumeController extends BaseController {

    @Value("${images.filePath}")
    String filePath;

    @Autowired
    private IItoResumeService itoResumeService;

    @Autowired
    private IItoPushService itoPushService;

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:resume:list')")
    @GetMapping("/list")
    public TableDataInfo list(ItoResume itoResume) {
        startPage();
        List<ItoResume> list = itoResumeService.selectItoResumeList(itoResume);
        return getDataTable(list);
    }

    /**
     * 导出简历列表
     */
    @PreAuthorize("@ss.hasPermi('system:resume:export')")
    @Log(title = "简历管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ItoResume itoResume) {
        List<ItoResume> list = itoResumeService.selectItoResumeList(itoResume);
        ExcelUtil<ItoResume> util = new ExcelUtil<ItoResume>(ItoResume.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取简历id详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:resume:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(itoResumeService.selectItoResumeById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:resume:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ItoResume itoResume) {
        return toAjax(itoResumeService.insertItoResume(itoResume));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:resume:push')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("push")
    public AjaxResult add(ItoPush itoPush) {
        return toAjax(itoPushService.insertItoPush(itoPush));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:resume:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ItoResume itoResume) {
        return toAjax(itoResumeService.updateItoResume(itoResume));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:resume:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(itoResumeService.deleteItoResumeByIds(ids));
    }


    /**
     * 淘汰
     */
    @PreAuthorize("@ss.hasPermi('system:resume:eliminate')")
    @Log(title = "【请点击淘汰】", businessType = BusinessType.DELETE)
    @DeleteMapping("eliminate/{ids}")
    public AjaxResult eliminate(@PathVariable Long[] ids) {
        return toAjax(itoResumeService.eliResume(ids));
    }

    /**
     * 推送
     */
    @PreAuthorize("@ss.hasPermi('system:resume:Push')")
    @Log(title = "【请点击推送】", businessType = BusinessType.DELETE)
    @DeleteMapping("Push/{ids}")
    public AjaxResult Push(@PathVariable ItoPush itoPush) {
        return toAjax(itoResumeService.PushResume(itoPush));
    }


    /**
     * 批量推送
     */
    @PreAuthorize("@ss.hasPermi('system:resume:batchPush')")
    @Log(title = "【请点击推送】", businessType = BusinessType.INSERT)
    @PostMapping("batchPush/{rids}/{pid}")
    public AjaxResult batchPush(@PathVariable Long[] rids, @PathVariable Long pid) {
        return toAjax(itoResumeService.pushResumes(rids, pid));
    }


    //然后是用日期来进行文件分配
    //这个格式，等下改一下试试看
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    @PreAuthorize("@ss.hasPermi('system:resume:upload')")
    @Log(title = "【请点击导入】", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public Map<String, Object> fileupload(MultipartFile file, HttpServletRequest req) throws Exception {
        //首先要给文件找一个目录
        //先写返回值
        Map<String, Object> result = new HashMap<>();
        //再用pdf格式开始书写,先找原始的名字
        String originName = file.getOriginalFilename();
        //判断文件类型是不是pdf
        if (!originName.endsWith(".pdf")) {
            //如果不是的话，就返回类型
            result.put("status", "error");
            result.put("msg", "文件类型不对");
            return result;
        }
        //如果是正确的话，就需要写保存文件的文件夹
        //.format(new Date())的意思是 也就是格式化一个新的时间
        //Date会创建一个时间，然后会按照当前的sdf格式调用format将当前时间创建出来 直接调用new Date()可能会出现这种格式
        //Sun Feb 28 10:55:06 CST 2021
        //再是getServletContext
        String format = file.getOriginalFilename();
        //这也是一个临时的路径，项目重启之后，他就会变的
        String realPath = "D://";
        //再是保存文件的文件夹
        File folder = new File(realPath);
        //如果不存在，就自己创建
        if (!folder.exists()) {
            folder.mkdirs();
        }

        String newName = file.getOriginalFilename() + ".pdf";

        //然后就可以保存了
        try {
            file.transferTo(new File(folder, newName));
            //这个还有一个url
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;
            //如果指向成功了
            result.put("status", "success");
            result.put("url", url);
        } catch (IOException e) {
            //返回异常
            result.put("status", "error");
            result.put("msg", e.getMessage());
        }
        return result;
    }

    @PreAuthorize("@ss.hasPermi('system:resume:uploads')")
    @Log(title = "导入", businessType = BusinessType.INSERT)
    @PostMapping("/uploads")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception {

        String fileName = file.getOriginalFilename();
        File file_dir = new File("d:/upload");
        if (!file_dir.exists()) {
            file_dir.mkdirs();
        }

        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        File desc = createAbsoluteFile("d:/upload", fileName);
        file.transferTo(desc);


        return AjaxResult.success("成功");
    }

    private static final File createAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }
        return desc;
    }

    @PreAuthorize("@ss.hasPermi('system:resume:file')")
    @Log(title = "【文件上传】", businessType = BusinessType.IMPORT)
    @PostMapping("file")
    public AjaxResult file(@RequestParam("file") MultipartFile file) throws InvalidExtensionException {

        return AjaxResult.success(itoResumeService.uploadFilePdf(file, filePath));
    }

    @PreAuthorize("@ss.hasPermi('system:resume:pieChartByYear')")
    @GetMapping("pieChartByYear")
    public AjaxResult pieChartSelectByYear(){
        List<PieResponseVo> pieResponseVos = itoResumeService.pieChartSelectByYear();
        return AjaxResult.success(pieResponseVos);
    }

    @PreAuthorize("@ss.hasPermi('system:resume:lineChartByYear')")
    @GetMapping("lineChartByYear")
    public AjaxResult lineChartSelectByYear(){
        LineResponseVo lineResponseVo = itoResumeService.LineChartSelectByYear();
        return AjaxResult.success(lineResponseVo);
    }

    @PreAuthorize("@ss.hasPermi('system:resume:pieChartByMonth')")
    @GetMapping("pieChartByMonth")
    public AjaxResult pieChartSelectByMonth(){
        List<PieResponseVo> pieResponseVos = itoResumeService.pieChartSelectByMonth();
        return AjaxResult.success(pieResponseVos);
    }

    @PreAuthorize("@ss.hasPermi('system:resume:lineChartByMonth')")
    @GetMapping("lineChartByMonth")
    public AjaxResult lineChartSelectByMonth(){
        LineResponseVo lineResponseVo = itoResumeService.LineChartSelectByMonth();
        return AjaxResult.success(lineResponseVo);
    }
}



